package com.hndct.interceptor;

import com.hndct.service.redis.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(HandlerInterceptor.class);
	
	@Autowired
	private RedisService redisService;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		//验证用户是否登录
		/*String token = req.getHeader("token");
		if(token == null){//header中没有token说明没登录
			req.getRequestDispatcher("/user/noLogin").forward(req, res);
			return false;
		}else{//有token，那么验证token有效性
			String userInfoJsonStr = redisService.get(token);
			if(userInfoJsonStr == null){//token无效
				req.getRequestDispatcher("/user/noLogin").forward(req, res);
				return false;
			}else{//token有效
				req.setAttribute("userInfoJsonStr", userInfoJsonStr);
				redisService.saveDataWithTime(token, userInfoJsonStr, Constant.userInfoInRedisTime);
				
				JSONObject fromObject = JSONObject.fromObject(userInfoJsonStr);
				int userId = fromObject.getInt("id");
				
				logger.info("userId{} {},路径{},get：{}",userId,new Date().toLocaleString(),req.getServletPath(),req.getQueryString());
			}
		}*/
		
		return true;
	}

}
